package com.thundersoft.beautifulmusic.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.thundersoft.beautifulmusic.R;
import com.thundersoft.beautifulmusic.entity.Song;
import com.thundersoft.beautifulmusic.util.SongUtil;

import java.util.List;

public class SongAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final List<Song> mSongs;
    private Context mContext;

    public SongAdapter(Context context, List<Song> songs) {
        mContext = context;
        mSongs = songs;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 这里需要MainActivity而不是真正的context
        View item = LayoutInflater.from(mContext).inflate(R.layout.item_song, parent, false);
        return new SongHolder(item);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        SongHolder songHolder = (SongHolder) holder;
        // 获得歌曲封面bitmap
        Song song = mSongs.get(position);
        Bitmap bitmap = SongUtil.optimizeSongBitmap(song.getAlbumId());
        songHolder.mCover.setImageBitmap(bitmap);
        songHolder.mName.setText(song.getName());
        songHolder.mSinger.setText(song.getSinger());
    }

    @Override
    public int getItemCount() {
        return mSongs.size();
    }

    static class SongHolder extends RecyclerView.ViewHolder {

        private final ImageView mCover;
        private final TextView mSinger;
        private final TextView mName;

        public SongHolder(@NonNull View itemView) {
            super(itemView);
            mCover = itemView.findViewById(R.id.song_cover);
            mSinger = itemView.findViewById(R.id.song_singer);
            mName = itemView.findViewById(R.id.song_name);
        }
    }
}
